<template>
  <div>
    <el-card>
      <div style="display: flex; align-items: center;">
        <el-image :src="tableData.url" style="width: 200px; height: 200px; margin-right: 24px;" />
        <div>
          <div><h2>{{ tableData.goodsName }}</h2></div><br/>
          <div>生产批次：{{tableData.batch}} <span style="margin-left: 60px;">保质期：{{ tableData.shelfLife }} 天</span></div><br/>
          <div>生产许可证号：{{tableData.licenseNumber }}<span style="margin-left: 60px;">生产企业：{{ tableData.enterprise }}</span></div><br/>
        </div>
      </div>
      <div style="margin-top: 16px;margin-left: 200px;">
        <div class="report-title">产品检验报告</div>
                        <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
                            list-type="picture-card" :file-list="reportList" :on-preview="handlePreview"
                            :on-remove="handleRemove" :on-success="handleAvatarSuccess" :limit="9"
                            :on-exceed="handleExceed"  multiple>
                            <el-icon>
                                <Plus/>
                            </el-icon>
                        </el-upload>
      </div>
    </el-card>
    <el-tabs v-model="activeTab"    style="margin-top: 24px;">  
      <el-tab-pane label="养殖信息" name="breeding">
        <div style="display: flex; align-items: center; margin-bottom: 8px;">
          <span style="font-weight: bold;color:blue;">养殖信息</span>
          <el-button size="small" style="margin-left: 8px;" @click="UpdateBreed">设置</el-button>
        </div>
        <hr/>
        <div>品种：{{ Breed.variety }}<span style="margin-left: 107px;">来源：{{ Breed.source}}</span></div><br/>
        <div>饲养天数：{{ Breed.feedingDays }}<span style="margin-left: 90px;">饲养品种：{{Breed.feedingBrand  }}</span></div><br/>
        <div>饲养负责人：{{Breed.feedingName  }}<span style="margin-left: 60px;">出栏日期：{{ Breed.saleDate ? moment(Breed.saleDate).format('YYYY年MM月DD日') : ''}}</span></div><br/>
        <hr/>
        <div style="margin-top: 16px;">
          <div style="display: flex; align-items: center; margin-bottom: 8px;">
            <span style="font-weight: bold;color:blue;">保健信息</span>
            <el-button size="small" style="margin-left: 8px;" @click="addHealthRow">新建行</el-button>
          </div>
          <el-table :data="healthList" border style="width: 100%; margin-top: 10px;">
                <el-table-column prop="feedingDays" label="饲养天数" width="250">
                    <template #default="scope">

                        <template v-if="scope.row.editing">
                            <el-input v-model="scope.row.editData.feedingDays" size="small" maxlength="5"
                                placeholder="必填，数字" />
                        </template>

                        <template v-else>
                            {{ scope.row.feedingDays }}
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="immuneSystem" label="保健方式" width="250">
                    <template #default="scope">
                        <template v-if="scope.row.editing">
                            <el-input v-model="scope.row.editData.immuneSystem" size="small" maxlength="30"
                                placeholder="必填，中文/字母" />
                        </template>
                        <template v-else>
                            {{ scope.row.immuneSystem }}
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="healthMethods" label="保健方法" width="250">
                    <template #default="scope">
                        <template v-if="scope.row.editing">
                            <el-input v-model="scope.row.editData.healthMethods" size="small" maxlength="30"
                                placeholder="必填，中文/字母" />
                        </template>
                        <template v-else>
                            {{ scope.row.healthMethods }}
                        </template>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="200">
                    <template #default="scope">

                        <template v-if="scope.row.editing">
                            <el-link type="primary" @click="saveRow(scope.row)">保存</el-link>
                            <el-link type="info" style="margin-left: 8px;" @click="cancelEdit(scope.row)">取消</el-link>
                        </template>

                        <template v-else>
                            <el-link type="primary" @click="editRow(scope.row)">修改</el-link>
                            <el-link type="danger" style="margin-left: 8px;" @click="deleteRow(scope.row)">删除</el-link>
                        </template>

                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="margin-top: 16px;">
          <span style="font-weight: bold;color:blue;">动检证</span>
                        <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
                            list-type="picture-card" :file-list="reportList1" :on-preview="handlePreview"
                            :on-remove="handleRemove" :on-success="handleAvatarSuccess2" :limit="9"
                            :on-exceed="handleExceed" multiple>
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
          <hr/>
        </div>
        <div style="margin-top: 24px;">
      <div style="display: flex; align-items: center;">
        <span style="font-weight: bold;color:blue;">养殖企业信息</span>
        <el-button size="small" style="margin-left: 8px;"@click="AddEnterprise">设置</el-button>
      </div>
      <hr/>
      <div>养殖场：{{Enterprise.farm  }}<span style="margin-left: 90px;">负责人：{{Enterprise.custodian }}</span></div><br/>
      <div>存栏数量：{{ Enterprise.feedNum }} 只</div><br/>
    </div>
    <div style="margin-top: 16px;">
        <div class="report-title" style="font-weight: bold;color:blue;">企业照片</div>
        <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
            list-type="picture-card" :file-list="reportList2" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess3" :limit="9"
            :on-exceed="handleExceed" multiple>
            <el-icon>
                <Plus/>
            </el-icon>
        </el-upload>
      </div>
      </el-tab-pane>

      <el-tab-pane label="屠宰信息"  name="slaughter">
        <div style="display: flex; align-items: center; margin-bottom: 8px;">
          <span style="font-weight: bold;color:blue;">屠宰信息</span>
          <el-button size="small" style="margin-left: 8px;" @click="Updateslaughter">设置</el-button>
        </div>
        <div>批次：{{ slaughter.batch}}<span style="margin-left: 216px;">到厂均重：{{ slaughter.weight }} 公斤</span></div><br/>
        <div>到厂时间：{{ slaughter.arrivalTime ? moment(slaughter.arrivalTime).format('YYYY年MM月DD日 hh:mm:ss') : ''}}<span style="margin-left: 107px;">屠宰时间：{{ slaughter.slaughterTime ? moment(slaughter.slaughterTime).format('YYYY年MM月DD日 hh:mm:ss') : ''}}</span></div>
        <div style="margin-top: 16px;">
          <span style="font-weight: bold;color:blue;">相关资质</span>
                        <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
                            list-type="picture-card" :file-list="reportList3" :on-preview="handlePreview"
                            :on-remove="handleRemove" :on-success="handleAvatarSuccess4" :limit="9"
                            :on-exceed="handleExceed" multiple>
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
          <hr/>
        </div>
        <div style="margin-top: 24px;">
      <div style="display: flex; align-items: center;">
        <span style="font-weight: bold;color:blue;">屠宰企业信息</span>
        <el-button size="small" style="margin-left: 8px;"@click="Updateslaughteringenterprise">设置</el-button>
      </div>
      <div>公司名称:{{slaughteringenterprise.corporateName}} <span style="margin-left: 60px;">成立时间：{{ slaughteringenterprise.establishmentTime ? moment(slaughteringenterprise.establishmentTime).format('YYYY年MM月DD日') : ''}}</span></div><br/>
      <div>公司地址: {{ codeToText[slaughteringenterprise.provincial] }}
                        {{ codeToText[slaughteringenterprise.market]  }}
                        {{ slaughteringenterprise.county }} </div><br/>
      <div>公司简介:{{ slaughteringenterprise.companyProfile }} </div>
    </div>
    <div style="margin-top: 16px;">
        <div class="report-title" style="font-weight: bold;color:blue;">企业照片</div>
        <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
            list-type="picture-card" :file-list="reportList4" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess5" :limit="9"
            :on-exceed="handleExceed" multiple>
            <el-icon>
                <Plus/>
            </el-icon>
        </el-upload>
      </div>
      </el-tab-pane>

      <el-tab-pane label="深加工信息"name="processing">
        <div style="display: flex; align-items: center; margin-bottom: 8px;"><br/>
          <span style="font-weight: bold;color: blue;">深加工工信息</span>
          <el-button size="small" style="margin-left: 8px;" @click="Updatedeepprocessing">设置</el-button>
        </div><br/>
        <div>班组：{{ deepprocessing.classgroup}}<span style="margin-left:107px;">负责人：{{deepprocessing.person}}</span></div><br/>

        <div style="margin-top: 24px;">
          <span style="font-weight: bold;color: blue;">食品安全信息</span>
          <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
            list-type="picture-card" :file-list="reportList5" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess6" :limit="9"
            :on-exceed="handleExceed" multiple>
            <el-icon>
                <Plus/>
            </el-icon>
        </el-upload>
        </div>

        <div style="margin-top: 24px;">
          <div style="display: flex; align-items: center;">
            <h2 style="font-weight: bold;color: blue;">供应商信息</h2> 
          </div>
            <div style="margin-bottom: 8px;" >原料  <el-button size="small" style="margin-left: 8px;" @click="supplierDialogVisible = true">设置</el-button></div><br/>
            <div>生产批次：{{ruleForm.batch }}</div>
            <div style="margin-top: 24px;">
              <h3 style="font-weight: bold;">相关材料</h3>
          <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
            list-type="picture-card" :file-list="reportList6" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess7" :limit="9"
            :on-exceed="handleExceed" multiple>
            <el-icon>
                <Plus/>
            </el-icon>
        </el-upload>
      </div>

          <div style="margin-top: 12px;">
            <div style="margin-bottom: 8px;">辅料 <el-button size="small" style="margin-left: 8px;" @click="supplierDialogVisible = true">设置</el-button></div><br/>
            
            <div>生产批次：{{ ruleForm.batch }}</div>
            <div style="margin-top: 24px;">
              <h3 style="font-weight: bold;">相关材料</h3>
          <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
            list-type="picture-card" :file-list="reportList7" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess8" :limit="9"
            :on-exceed="handleExceed" multiple>
            <el-icon>
                <Plus/>
            </el-icon>
        </el-upload>
      </div>

          </div>
          <div style="margin-top: 12px;">
            <div style="margin-bottom: 8px;">添加剂 <el-button size="small" style="margin-left: 8px;" @click="supplierDialogVisible = true">设置</el-button></div><br/>
            
            <div>生产批次：{{ ruleForm.batch }}</div>
            <div style="margin-top: 24px;">
              <h3 style="font-weight: bold;">相关材料</h3>
          <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
            list-type="picture-card" :file-list="reportList8" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess9" :limit="9"
            :on-exceed="handleExceed" multiple>
            <el-icon>
                <Plus/>
            </el-icon>
        </el-upload>
      </div>

          </div>
          <div style="margin-top: 12px;">
            <div style="margin-bottom: 8px;">包材 <el-button size="small" style="margin-left: 8px;" @click="supplierDialogVisible = true">设置</el-button></div><br/>
            
            <div>生产批次：{{ruleForm.batch }}</div>
            <div style="margin-top: 24px;">
              <h3 style="font-weight: bold;">相关材料</h3>
          <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
            list-type="picture-card" :file-list="reportList9" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess10" :limit="9"
            :on-exceed="handleExceed" multiple>
            <el-icon>
                <Plus/>
            </el-icon>
        </el-upload>
      </div>
          </div>
          
          <div style="margin-top: 24px;">
      <div style="display: flex; align-items: center;">
        <span style="font-weight: bold;color: blue;">企业信息 <el-button size="small" style="margin-left: 8px;"@click="Updatedeedeepprocessings">设置</el-button></span>
        
      </div><br/>
      <div>公司名称：{{ machiningEnterprise.corporateName}}<span style="margin-left:107px;">生成许可证号：{{machiningEnterprise.licenseNumber}}</span></div><br/>
     
    </div>
    <div style="margin-top: 16px;">
      <span style="font-weight: bold;">企业照片</span>
      <el-upload class="upload-demo" action="http://localhost:5050/api/UpFail/Upload"
            list-type="picture-card" :file-list="reportList10" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess11" :limit="9"
            :on-exceed="handleExceed" multiple>
            <el-icon>
                <Plus/>
            </el-icon>
        </el-upload>
    </div>
        </div>
      </el-tab-pane>
    </el-tabs>   
    <!-- 养殖信息弹窗 -->
    <el-dialog v-model="breedingDialogVisible" title="养殖信息" width="500px">
      <el-form :model="breedingForm" :rules="breedingFormRules" ref="breedingFormRef" label-width="120px">
        <el-form-item label="品种" prop="variety" required>
          <el-input
            v-model="breedingForm.variety"
            maxlength="30"
            show-word-limit
            placeholder="请输入品种"
            clearable
          />
        </el-form-item>
        <el-form-item label="来源" prop="source" required>
          <el-input
            v-model="breedingForm.source"
            maxlength="30"
            show-word-limit
            placeholder="请输入来源"
            clearable
          />
        </el-form-item>
        <el-form-item label="饲养天数" prop="feedingDays" required>
          <el-input
            v-model="breedingForm.feedingDays"
            maxlength="5"
            placeholder="请输入饲养天数"
            clearable
          />
        </el-form-item>
        <el-form-item label="饲养品种" prop="feedingBrand" required>
          <el-input
            v-model="breedingForm.feedingBrand"
            maxlength="30"
            show-word-limit
            placeholder="请输入饲养品种"
            clearable
          />
        </el-form-item>
        <el-form-item label="饲养负责人" prop="feedingName" required>
          <el-input
            v-model="breedingForm.feedingName"
            maxlength="30"
            show-word-limit
            placeholder="请输入负责人"
            clearable
          />
        </el-form-item>
        <el-form-item label="出栏日期" prop="saleDate" required>
          <el-date-picker
            v-model="breedingForm.saleDate"
            type="date"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
            placeholder="请选择出栏日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="breedingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBreeding">保存</el-button>
      </template>
    </el-dialog>
    <!-- 屠宰信息弹窗 -->
    <el-dialog v-model="slaughterDialogVisible"  title="屠宰信息" width="500px">
      <el-form :model="slaughterForm" :rules="enterpriseRules" label-width="120px">
        <el-form-item label="批次"><el-input v-model="slaughterForm.batch" /></el-form-item>
        <el-form-item prop="weight" label="到厂均重"><el-input-number  v-model="slaughterForm.weight" :min="1" /></el-form-item>
        <el-form-item prop="arrivalTime" label="到厂时间"><el-date-picker   v-model="slaughterForm.arrivalTime" type="datetime" /></el-form-item>
        <el-form-item prop="slaughterTime" label="屠宰时间"><el-date-picker   v-model="slaughterForm.slaughterTime" type="datetime" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="slaughterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveslaughter">保存</el-button>
      </template>
    </el-dialog>
    <!-- 深加工工信息弹窗 -->
    <el-dialog v-model="processingDialogVisible"  title="企业信息" width="500px">
      <el-form :model="pprocessing" :rules="deepprocessingRules"  label-width="120px">
        <el-form-item prop="classgroup" label="班组"><el-input    v-model="pprocessing.classgroup" /></el-form-item>
        <el-form-item  prop="person" label="负责人"><el-input  v-model="pprocessing.person" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addDeepprocessing">保存</el-button>
      </template>
    </el-dialog>
    <!-- 养殖企业信息弹窗 -->
    <el-dialog v-model="DialogVisible" title="企业信息" width="500px">
      <el-form :model="form" :rules="enterpriseFormRule" ref="companyFormRef" label-width="100px">
        <el-form-item label="公司名称" prop="farm" required>
          <el-input v-model="form.farm" maxlength="30" show-word-limit placeholder="请输入养殖场名称" />
        </el-form-item>
        <el-form-item label="负责人" prop="custodian" required>
          <el-input v-model="form.custodian"  style="width: 100%;" />
        </el-form-item>
        <el-form-item label="存栏数量（只）" prop="feedNum" required>
          <el-input v-model="form.feedNum" show-word-limit  />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="DialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addEnterprise">保存</el-button>
      </template>
    </el-dialog>
    <!-- 屠宰企业信息弹窗 -->
    <el-dialog v-model="companyDialogVisible" title="企业信息" width="500px">
      
      <el-form :model="companyForm" :rules="companyRules" ref="companyFormRef" label-width="100px">
        <el-form-item label="公司名称" prop="corporateName" required>
          <el-input v-model="companyForm.corporateName"  :rows="4" maxlength="300" show-word-limit placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="公司地址：" prop="address" class="anime-form-item">
        <!-- 省份选择 -->
        <el-select v-model="selectedProvince" placeholder="请选择省份" style="width: 40%;" clearable
        @change="handleProvinceChange">
        <el-option v-for="province in provinces" :key="province.value" :label="province.label"
        :value="province.value" />
        </el-select>

        <!-- 城市选择 -->
        <el-select v-model="selectedCity" placeholder="请选择城市" style="width: 40%;margin-left: 5px;" clearable
        :disabled="!selectedProvince" @change="handleCityChange">
        <el-option v-for="city in cities" :key="city.value" :label="city.label" :value="city.value" />
        </el-select>

        <!-- 具体地址输入选择 -->
        <el-input v-model="companyForm.county" style="width: 340px;margin-left: 5px;"
        class="anime-input" placeholder="请输入公司详细地址" />

</el-form-item>
        <el-form-item label="成立时间" prop="establishmentTime" required>
          <el-date-picker v-model="companyForm.establishmentTime" type="date" value-format="YYYY-MM-DD" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="公司简介" prop="companyProfile" required>
          <el-input v-model="companyForm.companyProfile" type="textarea" :rows="4" maxlength="300" show-word-limit placeholder="请输入公司简介" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="companyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveslaughteringenterprise">保存</el-button>
      </template>
    </el-dialog>
     <!-- 深加工企业信息弹窗 -->
     <el-dialog v-model="ShenDialogVisible" title="企业信息" width="500px">
      <el-form :model="machiningEnter" :rules="DeepprocessingsRules" ref="companyFormRef" label-width="100px">
        <el-form-item label="公司名称" prop="corporateName" required>
          <el-input v-model="machiningEnter.corporateName" maxlength="30" show-word-limit placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="生成许可证" prop="licenseNumber" required>
          <el-input v-model="machiningEnter.licenseNumber" placeholder="请输入许可证"  style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="companyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="adddeepprocessings">保存</el-button>
      </template>
    </el-dialog>
    <!-- 供应商信息弹窗 -->
    <el-dialog v-model="supplierDialogVisible" title="供应商信息" width="400px">
      <el-form :model="ruleForm" label-width="100px">
        <el-form-item label="生产批次"><el-input v-model="ruleForm.batch" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="supplierDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="supplierDialogVisible = false">保存</el-button>
      </template>
    </el-dialog>
  </div>
  <div><!-- 产品检验报告大图 -->
            <el-dialog v-model="dialogVisible" title="查看图片" class="anime-dialog" destroy-on-close append-to-body
                align-center>
                <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;padding:0;">
                    <img :src="dialogImageUrl" style="width:100%;height:100%;object-fit:contain;" />
                </div>
            </el-dialog>
        </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { regionData, codeToText } from 'element-china-area-data';
import axios from 'axios';
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus'
import moment from 'moment';
const activeTab = ref('breeding')
const breedingDialogVisible = ref(false)
const breedingFormRef = ref()
const ShenDialogVisible=ref(false)
const DialogVisible=ref(false)
const slaughterDialogVisible = ref(false)
const processingDialogVisible = ref(false)
const companyDialogVisible = ref(false)
const companyFormRef = ref()
const supplierDialogVisible = ref(false)

//多图片
//#region 
const reportList = ref<UploadUserFile[]>([])
const reportList1 = ref<UploadUserFile[]>([])
const reportList2 = ref<UploadUserFile[]>([])
const reportList3 = ref<UploadUserFile[]>([])
const reportList4 = ref<UploadUserFile[]>([])
const reportList5 = ref<UploadUserFile[]>([])
const reportList6 = ref<UploadUserFile[]>([])
const reportList7 = ref<UploadUserFile[]>([])
const reportList8 = ref<UploadUserFile[]>([])
const reportList9 = ref<UploadUserFile[]>([])
const reportList10 = ref<UploadUserFile[]>([])
  //#endregion

  //地址
  //#region 
//地址
// 省份数据
const provinces = ref(regionData);

// 选中的省份、城市、区县
const selectedProvince = ref('');
const selectedCity = ref('');
const selectedDistrict = ref('');
// 城市和区县数据
const cities = ref<any[]>([]);
const districts = ref<any[]>([]);
// 省份变化时的处理
const handleProvinceChange = (value: string) => {
    selectedCity.value = '';
    selectedDistrict.value = '';
    districts.value = [];

    if (value) {
        const province = provinces.value.find((p:any) => p.value === value);
        cities.value = province?.children || [];
    } else {
        cities.value = [];
    }
};

// 城市变化时的处理
const handleCityChange = (value: string) => {
    selectedDistrict.value = '';

    if (value && selectedProvince.value) {
        const province = provinces.value.find((p:any) => p.value === selectedProvince.value);
        const city = province?.children?.find((c:any) => c.value === value);
        districts.value = city?.children || [];
    } else {
        districts.value = [];
    }
    companyForm.provincial = selectedProvince.value
    companyForm.market = selectedCity.value
    console.log('选中的地区:', {
        province: selectedProvince.value,
        city: selectedCity.value,
        district: value
    });
};

//#endregion

//养殖信息字段
const breedingForm = reactive({
  id:0,
  batch:localStorage.getItem("batch")||"",
  variety: '',
  source: '',
  feedingDays: '',
  feedingName: '',
  feedingBrand: '',
  saleDate: '',
  createUserName:localStorage.getItem("accountName")||"",
  updateUserName:localStorage.getItem("accountName")||""
})

//删除图片
const handleRemove: UploadProps['onRemove'] = (uploadFile: any, uploadFiles) => {
    console.log(uploadFile)
    axios({
        url: 'http://localhost:5050/api/Price/DeletePicture',
        method: 'post',
        params: {
            Id: uploadFile.id
        }
    })
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message );
                GetproductsImg();
                GetproductsImg2();
                GetproductsImg3();
                GetproductsImg4();
                GetproductsImg5();
                GetproductsImg7(),
                GetproductsImg8(),
                GetproductsImg9(),
                GetproductsImg10(),
                GetproductsImg11()

            } else {
                ElMessage.error(res.data.message);
            }
        })
}

const handleExceed = () => {
    ElMessage.warning('最多上传9张图片')
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePreview = (file: any) => {
    dialogImageUrl.value = file.url || file.response?.url
    dialogVisible.value = true
}

//图片字段
const ruleForm = reactive({
  id:0,
  "batch": localStorage.getItem("batch")||"",
  "traceType":0,
  "imgType": 0,
  "imagepath": ""
})

//产检报告上传图片
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    ruleForm.imagepath = response
    ruleForm.traceType = 0,
    ruleForm.imgType = 1
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取产品检验报告图片
const GetproductsImg = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:0,
            imgType: 1,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                id:img.id,
                batch: img.batch,
                traceType:0,
                imgType: 1, // 图片的唯一标识: 1, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList.value);
        })
}

//动检证上传图片
const handleAvatarSuccess2: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 1,
  ruleForm.imgType = 1
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg2();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取动检证图片
const GetproductsImg2 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:1,
            imgType: 1,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList1.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:1,
                imgType: 1, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList1.value);
        })
}

//养殖企业上传图片
const handleAvatarSuccess3: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 1,
  ruleForm.imgType = 2
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg3();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取养殖企业图片
const GetproductsImg3 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:1,
            imgType: 2,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList2.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:1,
                imgType: 2, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList2.value);
        })
}

//屠宰资质上传图片
const handleAvatarSuccess4: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 2,
  ruleForm.imgType = 1
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg4();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取屠宰资质图片
const GetproductsImg4 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:2,
            imgType: 1,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList3.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:2,
                imgType: 1, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList3.value);
        })
}

//屠宰企业上传图片
const handleAvatarSuccess5: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 2,
  ruleForm.imgType = 2
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg5();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取屠宰企业图片
const GetproductsImg5 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:2,
            imgType: 2,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList4.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:2,
                imgType: 2, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList4.value);
        })
}

//食品安全上传图片
const handleAvatarSuccess6: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 3,
  ruleForm.imgType = 1
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg6();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取食品安全图片
const GetproductsImg6 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:3,
            imgType: 1,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList5.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:3,
                imgType: 1, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList5.value);
        })
}

//原料上传图片
const handleAvatarSuccess7: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 3,
  ruleForm.imgType = 2
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg7();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取原料图片
const GetproductsImg7 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:3,
            imgType: 2,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList6.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:3,
                imgType: 2, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList6.value);
        })
}

//原料上传图片
const handleAvatarSuccess8: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 3,
  ruleForm.imgType = 3
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg8();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取原料图片
const GetproductsImg8 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:3,
            imgType: 3,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList7.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:3,
                imgType: 3, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList7.value);
        })
}

//原料上传图片
const handleAvatarSuccess9: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 3,
  ruleForm.imgType = 4
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg9();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取原料图片
const GetproductsImg9 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:3,
            imgType: 4,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList8.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:3,
                imgType: 4, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList8.value);
        })
}

//原料上传图片
const handleAvatarSuccess10: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 3,
  ruleForm.imgType = 5
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg10();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取原料图片
const GetproductsImg10 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:3,
            imgType: 5,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList9.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:3,
                imgType: 5, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList9.value);
        })
}

//深加工企业上传图片
const handleAvatarSuccess11: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.imagepath = response,
  ruleForm.traceType = 3,
  ruleForm.imgType = 6
    axios.post('http://localhost:5050/api/Price/AddPicture', ruleForm)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message);
                GetproductsImg11();
            } else {
                ElMessage.error(res.data.message);
            }
        })
}

//获取深加工企业图片
const GetproductsImg11 = () => {
    axios.get('http://localhost:5050/api/Price/GetImmunity', {
        params: {
            batch: localStorage.getItem("batch"),
            traceType:3,
            imgType: 6,
        }
    })
        .then(res => {
          console.log('Response data:', res.data);
            // 格式化为el-upload的file-list格式
            reportList10.value = (res.data.data || []).map((img: any) => ({
                name: img.imagepath.split('/').pop(), // 文件名
                url: img.imagepath,
                batch: img.batch,
                id:img.id,
                traceType:3,
                imgType: 6, // 图片的唯一标识
            }))
            // 控制台输出调试
            console.log(reportList10.value);
        })
}

//养殖正则表达式
const breedingFormRules = {
  variety: [
    { required: true, message: '请输入品种', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请输入来源', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  feedingDays: [
    { required: true, message: '请输入饲养天数', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '请输入最多5位数字', trigger: 'blur' }
  ],
  feedingBrand: [
    { required: true, message: '请输入饲养品种', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  feedingName: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  saleDate: [
    { required: true, message: '请选择出栏日期', trigger: 'change' }
  ]
}

//养殖企业正则表达式
const enterpriseFormRule = {
  farm: [
    { required: true, message: '请输入养殖场', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  custodian: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  feedNum: [
    { required: true, message: '请输入存栏数量', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '请输入最多5位数字', trigger: 'blur' }
  ],
}

//反填溯源信息
const Page=reactive({
  totalPage:0,
  totalCount:0,
  PageIndex:1,
  PageSize:1,
  batch:localStorage.getItem("batch")||"",
})

//溯源信息
const tableData:any=reactive({
  "id": 0,
  "batch": "",
  "shelfLife": 0,
  "licenseNumber": "",
  "enterprise": "",
  "url": "",
  "percentage": 0,
  "goodsName": "",
})

//溯源反填方法
const getTraceablity=()=>{
  axios.get("http://localhost:5050/api/Maxage/GetAccount",{params:{
    PageIndex:Page.PageIndex,
    PageSize:Page.PageSize,
    batch:Page.batch,
  }})
.then(res=>{
  tableData.value=res.data.data.data
  tableData.id=res.data.data.data.id
  tableData.batch=res.data.data.data[0].batch
  tableData.shelfLife=res.data.data.data[0].shelfLife
  tableData.licenseNumber=res.data.data.data[0].licenseNumber
  tableData.enterprise=res.data.data.data[0].enterprise
  tableData.url=res.data.data.data[0].url
  tableData.percentage=res.data.data.data[0].percentage
  tableData.goodsName=res.data.data.data[0].goodsName
  Page.totalCount=res.data.data.data[0].totalCount
  Page.totalPage=res.data.data.data[0].totalPage
})
}

//生命周期钩子
onMounted(()=>{
  Promise.all([
  getTraceablity(),
  getBear(),
  GetHandle(),
  getEnterprise(),
  GetproductsImg(),
  GetproductsImg2(),
  GetproductsImg3(),
  getslaughter(),
    GetproductsImg4(),
    GetproductsImg5(),
    getslaughteringenterprise(),
    getDeepprocessing(),
    GetproductsImg6(),
    GetproductsImg7(),
    GetproductsImg8(),
    GetproductsImg9(),
    GetproductsImg10(),
    GetproductsImg11(),
    getMachiningEnterprise()
]);
})

//养殖信息
const Breed:any=reactive({
      id:"",
      "batch": "",
      "variety": "",
      "source": "",
      "feedingDays": '',
      "feedingBrand": "",
      "feedingName": "",
      "saleDate": "",
})

//获取养殖信息
const getBear=()=>{
  axios.get("http://localhost:5050/api/Breeds/GetBreed",{params:{
    batch:Page.batch,
  }})
.then(res=>{
  Breed.value=res.data.data
  Breed.id=res.data.data[0].id
  Breed.batch=res.data.data[0].batch
  Breed.variety=res.data.data[0].variety
  Breed.source=res.data.data[0].source
  Breed.feedingDays=res.data.data[0].feedingDays
  Breed.feedingBrand=res.data.data[0].feedingBrand
  Breed.feedingName=res.data.data[0].feedingName
  Breed.saleDate=res.data.data[0].saleDate
})
}

//修改方法
const UpdateBreed=()=>{
  if (Breed.value != null) 
{
  breedingForm.id=Breed.id,
  breedingForm.variety=Breed.variety,
  breedingForm.source=Breed.source,
  breedingForm.feedingDays=Breed.feedingDays,
  breedingForm.feedingBrand=Breed.feedingBrand,
  breedingForm.feedingName=Breed.feedingName,
  breedingForm.saleDate=Breed.saleDate
}
else{
 
}
breedingDialogVisible.value = true
}

//养殖信息添加
const saveBreeding=()=>{
 if(Breed.id == 0)
 {
  axios.post("http://localhost:5050/api/Breeds/AddBreed", breedingForm)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      breedingDialogVisible.value = false
      getBear();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
 else
 {
  axios.put("http://localhost:5050/api/Breeds/UpdateBreed", breedingForm)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      breedingDialogVisible.value = false
      getBear();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
}

const healthList: any = ref([])

//获取保健信息
const GetHandle = () => {
    axios.get('http://localhost:5050/api/Breeds/GetImmunity', {
        params: {
          batch: localStorage.getItem("batch")||""
        }
    })
        .then(res => {
            // 处理后端数据，补充辅助字段
            healthList.value = (res.data.data || []).map((item: any) => ({
                ...item,
                editing: false,
                isNew: false,
                editData: {
                    id: '',
                    batch: localStorage.getItem("batch"),
                    feedingDays: "",
                    immuneSystem: "",
                    healthMethods: ""
                }
            }))
            console.log(healthList.value);

        })
}

//新建行
const addHealthRow=()=>{
  healthList.value.push({
        editing: true,
        isNew: true,
        editData: {
            Id: '',
            batch: localStorage.getItem("batch")||"",
            feedingDays: '',
            immuneSystem: "",
            healthMethods: "",
            createUserName:localStorage.getItem("accountName")||"",
            deleteUserName:"",
        }
    })
}

// 编辑行
const editRow = (row: any) => {
    row.editing = true
    isadd.value = true
    row.editData = {
        batch: row.batch,
        feedingDays: row.feedingDays,
        immuneSystem: row.immuneSystem,
        healthMethods: row.healthMethods,
        createUserName:row.createUserName,
        updateUserName:localStorage.getItem("accountName")||"",
        id: row.id
    }

}

// 删除行
const deleteRow = (row: any) => {
  ElMessageBox.confirm(
        '确定要删除吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post('http://localhost:5050/api/Breeds/DeleteImmunity?Id='+row.id 
            )
           
                .then(res => {
                    if (res.data.code == 200) {
                     
                        ElMessage.success(res.data.message);
                        GetHandle();
                    }
                    else {
                        ElMessage.error(res.data.message);
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}

// 取消编辑
const cancelEdit = (row: any) => {
    if (row.isNew) {
        healthList.value.splice(healthList.value.indexOf(row), 1)
    } else {
        row.editing = false
    }
}

const isadd: any = ref(false)

// 保存行
const saveRow = (row: any) => {
    const { feedingDays, immuneSystem, healthMethods } = row.editData
    if (!feedingDays || !immuneSystem || !healthMethods) {
        ElMessage.warning('请填写完整信息')
        return
    }
    if (!/^[0-9]{1,5}$/.test(feedingDays)) {
        ElMessage.warning('饲养天数仅允许输入1-5位数字')
        return
    }
    if (!/^[\u4e00-\u9fa5a-zA-Z]{1,30}$/.test(immuneSystem)) {
        ElMessage.warning('保健方式仅允许输入中文或字母，且不超过30位')
        return
    }
    if (!/^[\u4e00-\u9fa5a-zA-Z]{1,30}$/.test(healthMethods)) {
        ElMessage.warning('保健方法仅允许输入中文或字母，且不超过30位')
        return
    }
    console.log(healthList.value.editData);

    if (isadd.value == false) {
        axios({
            url: 'http://localhost:5050/api/Breeds/AddImmunity',
            method: 'post',
            data: row.editData
        })
            .then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                   
                    GetHandle();
                }
                else {
                    ElMessage.error(res.data.message);
                }
            })
            healthList.value.editData= false
    }
    else {
        axios({
            url: 'http://localhost:5050/api/Breeds/UpdateImmunity',
            method: 'put',
            data: row.editData
        })
            .then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    GetHandle();
                }
                else {
                    ElMessage.error(res.data.message);
                }
            })
    }
}

const AddEnterprise=()=>{
  if (Enterprise.value != null) 
{
  form.id=Enterprise.id,
  form.custodian=Enterprise.custodian,
  form.feedNum=Enterprise.feedNum,
  form.farm=Enterprise.farm
}
else{
 
}
DialogVisible.value = true
}

//养殖企业字段
const Enterprise:any=reactive({
      id:'',
      "batch": "",
      "custodian": "",
      "feedNum": 0,
      "farm": "",
})

//获取养殖企业信息
const getEnterprise=()=>{
  axios.get("http://localhost:5050/api/Breeds/GetEnterprise",{params:{
    batch:Page.batch,
  }})
.then(res=>{
  Enterprise.value=res.data.data
  Enterprise.id=res.data.data[0].id
  Enterprise.batch=res.data.data[0].batch
  Enterprise.custodian=res.data.data[0].custodian
  Enterprise.farm=res.data.data[0].farm
  Enterprise.feedNum=res.data.data[0].feedNum
})
}

//养殖企业添加字段
const form = reactive({
  id:0,
  batch:localStorage.getItem("batch")||"",
  farm: '',
  custodian: '',
  feedNum: '',
  createUserName:localStorage.getItem("accountName")||"",
  updateUserName:localStorage.getItem("accountName")||""
})

//养殖企业添加
const addEnterprise=()=>{
 if(form.id==0)
 {
  axios.post("http://localhost:5050/api/Breeds/AddEnterprise",form)
    .then(res=>{form
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      DialogVisible.value = false
      getEnterprise ();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
 else
 {
  axios.put("http://localhost:5050/api/Breeds/UpdateEnterprise",form)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      DialogVisible.value = false
      getEnterprise();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
}

//班组正则表达式
const enterpriseRules = {
  weight: [
    { required: true, message: '请输入饲养天数', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '请输入最多5位数字', trigger: 'blur' }
  ],
  arrivalTime: [
    { required: true, message: '请选择出栏日期', trigger: 'change' }
  ],
  slaughterTime: [
    { required: true, message: '请选择出栏日期', trigger: 'change' }
  ]
}

//屠宰信息字段
const slaughterForm = reactive({
  id:0,
  batch:localStorage.getItem("batch")||"",
  weight:'',
  arrivalTime:'',
  slaughterTime:'',
  createUserName:localStorage.getItem("accountName")||"",
  updateUserName:localStorage.getItem("accountName")||""
})

//屠宰信息
const slaughter:any=reactive({
      id:"",
      "batch": "",
      "weight": "",
      "arrivalTime": "",
      "slaughterTime": '',
})

//获取屠宰信息
const getslaughter=()=>{
  axios.get("http://localhost:5050/api/Slaughter/GetSlaughter",{params:{
    batch:Page.batch,
  }})
.then(res=>{
  slaughter.value=res.data.data
  slaughter.id=res.data.data[0].id
  slaughter.batch=res.data.data[0].batch
  slaughter.weight=res.data.data[0].weight
  slaughter.arrivalTime=res.data.data[0].arrivalTime
  slaughter.slaughterTime=res.data.data[0].slaughterTime

})
}

const Updateslaughter=()=>{
  if (slaughter.value != null) 
{
  slaughterForm.id=slaughter.id,
  slaughterForm.weight=slaughter.weight,
  slaughterForm.arrivalTime=slaughter.arrivalTime,
  slaughterForm.slaughterTime=slaughter.slaughterTime
}
else{
 
}
slaughterDialogVisible.value = true
}
  
  //屠宰信息添加
const saveslaughter=()=>{
 if(slaughter.id == 0)
 {
  axios.post("http://localhost:5050/api/Slaughter/AddSlaughter", slaughterForm)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      slaughterDialogVisible.value = false
      getslaughter();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
 else
 {
  axios.put("http://localhost:5050/api/Slaughter/UpdateSlaughter", slaughterForm)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      slaughterDialogVisible.value = false
      getslaughter();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
}

//屠宰企业信息字段
const companyForm = reactive({
  id:0,
  batch:localStorage.getItem("batch")||"",
  corporateName:'',
  provincial:'',
  market:'',
  county:'',
  establishmentTime:'',
  companyProfile:'',
  createUserName:localStorage.getItem("accountName")||"",
  updateUserName:localStorage.getItem("accountName")||""
})

//屠宰企业正则
const companyRules = {
  corporateName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请选择公司地址', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  establishmentTime: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  companyProfile: [
    { required: true, message: '请输入公司简介', trigger: 'blur' },
    { min: 1, max: 300, message: '最多300位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],

}

//屠宰企业信息
const slaughteringenterprise:any=reactive({
      id:"",
      "batch": "",
      "corporateName": "",
      "provincial": "",
      "market": "",
      "county": '',
      "establishmentTime": '',
      "companyProfile": '',
})

//获取企业屠宰信息
const getslaughteringenterprise=()=>{
  axios.get("http://localhost:5050/api/Slaughter/Getslaughteringenterprise",{params:{
    batch:Page.batch,
  }})
.then(res=>{
  slaughteringenterprise.value=res.data.data
  slaughteringenterprise.id=res.data.data[0].id
  slaughteringenterprise.batch=res.data.data[0].batch
  slaughteringenterprise.corporateName=res.data.data[0].corporateName
  slaughteringenterprise.provincial=res.data.data[0].provincial
  slaughteringenterprise.market=res.data.data[0].market
  slaughteringenterprise.county=res.data.data[0].county
  slaughteringenterprise.establishmentTime=res.data.data[0].establishmentTime
  slaughteringenterprise.companyProfile=res.data.data[0].companyProfile

})
}

const Updateslaughteringenterprise=()=>{
  if (slaughteringenterprise.value != null) 
{
  companyForm.id=slaughteringenterprise.id,
  companyForm.corporateName=slaughteringenterprise.corporateName,
  companyForm.provincial=slaughteringenterprise.provincial,
  companyForm.market=slaughteringenterprise.market
  companyForm.county=slaughteringenterprise.county
  companyForm.establishmentTime=slaughteringenterprise.establishmentTime
  companyForm.companyProfile=slaughteringenterprise.companyProfile
  selectedProvince.value = companyForm.provincial
        handleProvinceChange(selectedProvince.value)
        selectedCity.value = companyForm.market
        handleCityChange(selectedCity.value)
}
else{
 
}
companyDialogVisible.value = true
}

  //屠宰企业信息添加
const saveslaughteringenterprise=()=>{
 if(slaughteringenterprise.id == 0)
 {
  axios.post("http://localhost:5050/api/Slaughter/Addslaughteringenterprise", companyForm)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      companyDialogVisible.value = false
      getslaughteringenterprise();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
 else
 {
  axios.put("http://localhost:5050/api/Slaughter/Updateslaughteringenterprise", companyForm)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      companyDialogVisible.value = false
      getslaughteringenterprise();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
}

//班组企业字段
const deepprocessing:any=reactive({
  id:'',
  batch:"",
  classgroup: '',
  person: '',
})

//获取班组信息
const getDeepprocessing=()=>{
  axios.get("http://localhost:5050/api/Deepprocessings/GetDeepprocessings",{params:{
    batch:Page.batch,
  }})
.then(res=>{
  deepprocessing.value=res.data.data;
  deepprocessing.id=res.data.data[0].id;
  deepprocessing.classgroup=res.data.data[0].classgroup;
  deepprocessing.person=res.data.data[0].person;

})
}

//班组添加字段
const pprocessing = reactive({
  id:0,
  batch:localStorage.getItem("batch")||"",
  classgroup: '',
  person: '',
  createUserName:localStorage.getItem("accountName")||"",
  updateUserName:localStorage.getItem("accountName")||""
})

//班组反填
const Updatedeepprocessing=()=>{
  if (deepprocessing.value != null) 
{
  pprocessing.id=deepprocessing.id,
  pprocessing.classgroup=deepprocessing.classgroup,
  pprocessing.person=deepprocessing.person
}
else{
}
processingDialogVisible.value = true
}

//班组添加 
const addDeepprocessing=()=>{
 if(pprocessing.id==0)
 {
  axios.post("http://localhost:5050/api/Deepprocessings/AddDeepprocessing",pprocessing)
    .then(res=>{form
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      processingDialogVisible.value = false
      getEnterprise ();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
 else
 {
  axios.put("http://localhost:5050/api/Deepprocessings/UpdateDeepprocessing",pprocessing)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      processingDialogVisible.value = false
      getEnterprise();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
}

//班组正则表达式
const deepprocessingRules = {
  classgroup: [
  { required: true, message: '请输入班组', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\u0020]+$/, message: '请输入有效的字符', trigger: 'blur' },
    { max: 30, message: '最多30个字符', trigger: 'blur' }
  ],
  person: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
}

//深加工正则表达式
const DeepprocessingsRules = {
  corporateName: [
  { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 1, max: 30, message: '最多30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '仅限中文或字母', trigger: 'blur' }
  ],
  licenseNumber: [
  { required: true, message: '请输入内容', trigger: 'blur' },
  { pattern: /^[a-zA-Z0-9]{1,30}$/, message: '只允许输入数字、字母，且最多30个字符', trigger: 'blur' }
  ]
}

//深加工企业字段
const machiningEnterprise:any=reactive({
  id:'',
  batch:"",
  corporateName: '',
  licenseNumber: '',
})

//获取深加工企业信息
const getMachiningEnterprise=()=>{
  axios.get("http://localhost:5050/api/Deepprocessings/GetMachiningEnterprise",{params:{
    batch:Page.batch,
  }})
.then(res=>{
  machiningEnterprise.value=res.data.data;
  machiningEnterprise.id=res.data.data[0].id;
  machiningEnterprise.corporateName=res.data.data[0].corporateName;
  machiningEnterprise.licenseNumber=res.data.data[0].licenseNumber;

})
}

//深加工企业添加字段
const machiningEnter = reactive({
  id:0,
  batch:localStorage.getItem("batch")||"",
  corporateName: '',
  licenseNumber: '',
  createUserName:localStorage.getItem("accountName")||"",
  updateUserName:localStorage.getItem("accountName")||""
})

//深加工企业反填
const Updatedeedeepprocessings=()=>{
  if (machiningEnterprise.value != null) 
{
  machiningEnter.id=machiningEnterprise.id,
  machiningEnter.corporateName=machiningEnterprise.corporateName,
  machiningEnter.licenseNumber=machiningEnterprise.licenseNumber
}
else{
}
ShenDialogVisible.value = true
}

//深加工企业添加
const adddeepprocessings=()=>{
 if(machiningEnter.id==0)
 {
  axios.post("http://localhost:5050/api/Deepprocessings/AddMachiningEnterprise",machiningEnter)
    .then(res=>{form
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      ShenDialogVisible.value = false
      getMachiningEnterprise ();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
 else
 {
  axios.put("http://localhost:5050/api/Deepprocessings/UpdateMachiningEnterprise",machiningEnter)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      ShenDialogVisible.value = false
      getMachiningEnterprise();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
 }
}


</script>

<script lang="ts">
export default {
  name: 'TraceabilityDetail',
}

</script> 
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>